package com.capgemini.simpleappblanche.dao.security.impl;

import static org.springframework.util.Assert.notNull;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.capgemini.simpleappblanche.dao.security.IUserDao;
import com.capgemini.simpleappblanche.domain.security.User;
import com.capgemini.simpleappblanche.utils.AbstractDaoJpaBase;

/**
 * Hibernate-based {@link AccountDao} implementation.
 * 
 * @author Willie Wheeler (willie.wheeler@gmail.com)
 */
@Repository
public class UserDao extends AbstractDaoJpaBase<User, Long> implements IUserDao {

    /**
     * {@inheritDoc}
     * @see com.springinpractice.ch07.dao.AccountDao#getByUsername(java.lang.String)
     */
    @Override
    public User getByUsername(String username) {
        notNull(username, "username can't be null");
        return (User) getEntityManager().createNamedQuery("user.byUsername").setParameter("username", username)
                .getSingleResult();
    }

    /**
     * {@inheritDoc}
     * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
     */
    @Override
    @Transactional
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        notNull(username, "username can't be null");
        User user= getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("No user with username " + username);
        }
        return user;
    }
}
